import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Table, Space, Button, Drawer, Tag, Modal } from 'antd'
import type { ColumnsType, TablePaginationConfig } from 'antd/es/table';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import './index.scss'

import SearchForm from '@/components/Form/SearchForm';
import TableList from '@/components/TableList/TableList';
import Detail from './components/Detail';

import { searchList, buttonList } from "./option"

import ListApi from './api/list';
import { type } from '@/utils/options';
import confirmDialog from '@/utils/confirmDialog';
const listApi = new ListApi()


const Order: React.FC = () => {
    const { confirm } = Modal;
    const navigate = useNavigate()
    const columns: ColumnsType<any> = [
        {
            title: '序号',
            render: (text, record, index) => `${index + 1}`,
        },
        {
            title: 'id',
            dataIndex: 'id',
            key: 'id',
        },
        {
            title: '名称',
            dataIndex: 'name',
            key: 'name',
        },

        {
            title: '分类',
            dataIndex: 'type',
            key: 'type',
            render: (_: any, { type }: any) => (
                <Space size="middle">
                    <div>{type.label}</div>
                </Space>
            ),
        },
        {
            title: '类型',
            dataIndex: 'label',
            key: 'label',
            render: (_: any, { label }: any) => {
                let color;
                switch (label) {
                    case 0:
                        color = 'red';
                        break;
                    case 1:
                        color = 'green';
                        break;
                }
                return (
                    <Tag color={color} key={label}>
                        {type[label]}
                    </Tag>
                )
            }
        },
        {
            title: '价格',
            dataIndex: 'price',
            key: 'price',
            render: (_: any, record: any) => (
                <Space size="middle">
                    <div>{record.label == 0 ? '- ¥' + record.price : '+ ¥' + record.price}</div>
                </Space>
            ),
        }, {
            title: '预算',
            dataIndex: 'budget',
            key: 'budget',
            render: (_: any, record: any) => (
                <Space size="middle">
                    <div>¥{record.budget}</div>
                </Space>
            ),
        }, {
            title: '余额',
            dataIndex: 'balance',
            key: 'balance',
        }, {
            title: '姓名',
            dataIndex: 'username',
            key: 'username',
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
        },
        {
            title: '操作',
            key: 'action',
            render: (_: any, record: any) => (
                <Space size="middle">
                    <a onClick={() => modifyIAE(record)}>编辑</a>
                    <a onClick={() => deleteIAE(record.id)} style={{ color: 'red' }}>删除</a>
                </Space>
            ),
        },
    ];

    // 列表数据
    const [data, setData] = useState<any[]>();
    const [search, setSearch] = useState(searchList)
    // 分页信息
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
        total: 0
    })
    const [typeList, setTypeList] = useState<any>();
    const [initialValues, setInitialValues] = useState<any>()
    const [title, setTitle] = useState<any>()

    // 打开详情页
    const [open, setOpen] = useState(false);

    // 获取列表数据
    const getData = (value?: any) => {
        if (value && value.createTime) {
            value.createTime = value.createTime.format('YYYY-MM-DD 23:59:59')
        }

        let params = {
            data: value,
            current: pagination.current,
            pageSize: pagination.pageSize
        }
        listApi.queryList(params).then((res) => {
            if (res) {
                setData(res.data)
                let page = pagination
                page.total = res.totalCount
                setPagination(page)
            }
        })
    }

    // 获取分类信息
    const getType = () => {
        listApi.typeList().then((res) => {
            let searchL = [...search]
            if (res) {
                let typeList = res.map((item: any) => {
                    return Object.assign({}, { 'value': item.id, 'label': item.name })
                })
                setTypeList(typeList)
                searchL.map((item: any) => {
                    if (item.label === '类型') {
                        item.options = typeList
                    }
                })
                setSearch(searchL)
            }
        })
    }

    //监听翻页数据变化
    const pageChange = (current: number, pageSize: number) => {
        let page = pagination
        page.current = current
        page.pageSize = pageSize
        setPagination(page)
        getData()
    }
    //当前页面页码发生变化
    const currentChange = (current: number) => {
        let page = pagination
        page.current = current
        setPagination(page)
        getData()
    }

    // 点击筛选
    const onQuery = (values: any) => {
        console.log(values);
        getData(values)
    };

    // 新增
    const onAdd = () => {
        setTitle('新增收支')
        setInitialValues({})
        setOpen(true);
    }
    // 导出
    const exportData = () => {
        console.log("导出成功")
    }

    // 编辑
    const modifyIAE = (record: any) => {
        setTitle('编辑收支')
        setInitialValues(record)
        setOpen(true);
    }

    //删除
    const deleteIAE = (id: string) => {
        confirmDialog('确认删除？', () => {
            let list = data
            listApi.delete(id).then((res) => {
                if (list) {
                    list = list.filter((item: any) => {
                        return item.id != id
                    })
                }
                setData(list)
            })
        })
    }

    // 重置
    const onReset = () => {
        getData()
    }

    // 关闭详情页
    const onClose = () => {
        setOpen(false);
    };

    //提交新增/编辑信息
    const submitDetail = (value: any) => {
        if (value.id) {
            //编辑
            listApi.edit(value).then((res) => {
                if (res) {
                    getData()
                }
            })
        } else {
            //新增
            listApi.add(value).then((res) => {
                if (res) {
                    getData()
                }
            })
        }
        setOpen(false);
    }

    // 副作用
    useEffect(() => {
        // 获取分类信息
        getType()
        // 获取列表信息
        getData()
    }, []);


    return (
        <div>
            {/* 搜素栏 */}
            <SearchForm searchList={search} buttonList={buttonList} onQuery={onQuery} onExport={exportData} onReset={onReset}>
                <Button type="primary" htmlType="button" onClick={onAdd} style={{ marginLeft: 20 }}>
                    新增
                </Button>
            </SearchForm>

            {/* 数据列表 */}
            <TableList columns={columns} initData={data} pagination={pagination} pageChange={pageChange} currentChange={currentChange}></TableList>


            {/* 详情页 */}
            <Drawer
                title={title}
                onClose={onClose}
                open={open}
                destroyOnClose={true}
                bodyStyle={{ paddingBottom: 80 }}
            >
                <Detail initialValues={initialValues} onCancel={onClose} onSubmit={submitDetail} typeList={typeList}></Detail>
            </Drawer>
        </div >
    )
}

export default Order